package com.linran.poll.service.impl;

import com.linran.poll.service.ILongPollingService;
import com.linran.poll.service.loop.LoopPullTask;
import com.linran.poll.service.loop.LoopPushTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Service
public class LongPollingServiceImpl implements ILongPollingService {
    @Autowired
    private ScheduledExecutorService schedule;
    private LoopPullTask loopPullTask;


    /*必须要先poll，每次poll都是创建新的LoopPollTask对象*/

    @Override
    public String pull() {
        loopPullTask = new LoopPullTask();
        ScheduledFuture<String> result = this.schedule.schedule(loopPullTask, 0L, TimeUnit.SECONDS);
        try {
            return result.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ex";
    }

    @Override
    public String push(String data) {
        ScheduledFuture<String> result = this.schedule.schedule(new LoopPushTask(loopPullTask, data), 0L, TimeUnit.SECONDS);
        try {
            return result.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ex";
    }
}
